<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/include/taglib.jsp"%>
<html>
	<head>
		<meta charset="UTF-8">
		<title>我要投资-月利宝详情|购买</title>
		<jsp:include page="/include/wchat/head.jsp"></jsp:include>

		<link type="text/css" rel="stylesheet"
			href="/v2/wchat/resrc/css/invest.css">
	</head>
	<body>
		<div id="header">
			<a href="/wchatYlbDetail.do?pid=${productDetailMap.pid}"
				class="backto">返回</a>
			<div class="title-sub">
				月利宝详情
			</div>
		</div>
		<div id="wrap">
			<div class="invest-detail">
				<b class="icon-qiang"></b>
				<h1>


					月利宝 ${productDetailMap.SN }

				</h1>
				<ul class="items">
					<li class="c1">
						可购金额
					</li>
					<li class="c2">
						￥${productDetailMap.remain}
					</li>
				</ul>
				<ul class="items">
					<li class="c1">
						账户余额
					</li>
					<li class="c2">
						￥
						<s:if test="#request.accmountStatisMap.usableSum !=''">${accmountStatisMap.usableSum}</s:if>
						<s:else>0</s:else>
						<input type="hidden" id="realnameFlag"
							value="${session.user.isBindIdNo}">
					</li>
				</ul>
				<ul class="items">
					<li class="c1">
						安全保障
					</li>
					<li class="c2 safe">
						100%本息保障
					</li>
				</ul>
			</div>
			<div class="invest-buy">
				<ul>
					<li class="money">
						<label class="txt">
							购买金额
						</label>
						<input class="input" id="inputAmount" maxlength="8"
							placeholder="请输入50~${productDetailMap.remain}的整数" onkeyup="calAvailableVoucherAmount();">
					</li>
					
					<s:if test="#request.availableVoucherList.size>0">
					<li class="novice">
						<label for="novice-chk">
							<input class="ipt-chk" id="novice-chk"
								type="checkbox" checked="checked">
							使用共富券
						</label>
						<select id="voucherSelect">
							<s:iterator value="#request.availableVoucherList" var="availableVoucher" status="s">
								<option value="${availableVoucher.id }" id="voucher${availableVoucher.id }">
								投资抵用券 ￥${availableVoucher.remainMoney }
								</option>
							</s:iterator>
						</select>
						<s:iterator value="#request.availableVoucherList" var="availableVoucher" status="s">
							<span id="availableVoucherAmount" class="availableVoucherAmount"
								voucherid="${availableVoucher.id}" leftamount="${availableVoucher.remainMoney }" 
								voucherType="${availableVoucher.voucherType}" discountratio="${availableVoucher.exchangeRate}" 
								typetitle="投资抵用券"></span>
						</s:iterator>
					</li>
					</s:if>

					<li class="verify">
						<span class="verify-code"> <input type="text" id="authCode"
								class="input" maxlength="4" placeholder="请输入验证码"> </span>
						<img
							src="I4008lOve893gOfUll983/imageCode.do?pageId=ylbWchatInvest"
							onclick="coderefresh()" id="verifyCodeImg">
					</li>
					<li class="argee">
						<input type="checkbox" id="agreeContract" class="ipt-chk"
							checked="checked">
						我同意《
						<a href="/getMessageBytypeId.do?typeId=22">共富网投资咨询与管理服务协议</a>》
					</li>
				</ul>
				<div class="vtip" id="errorTip"></div>
			</div>
			<div class="operate-button operate-buy">
				<a href="javascript:invest();" class="btn" id="investBt">我要购买</a>
				<a href="/wchatRealNameAuthen.do" class="btn" id="realNameBt"
					style="display: none;">立即实名认证</a>
			</div>
		</div>
		<jsp:include page="/include/wchat/footer.jsp"></jsp:include>

<script type="text/javascript">
var product = {
		aunualInterestRate : '${productDetailMap.productAnnualRate}',
		remain : '${productDetailMap.remain}',
		id : '${productDetailMap.pid}'
	};
environment.userCash = '${accmountStatisMap.usableSum}';
$(function(){
  $('#agreeContract').click(function(){
    if ($('#agreeContract').attr("checked") == "checked") {
      $('#agreeContract').removeAttr("checked");
    } else {
      $('#agreeContract').attr("checked", "checked");
    }
  });
  $('#novice-chk').click(function(){
	    if ($('#novice-chk').attr("checked") == "checked") {
	      $('#novice-chk').removeAttr("checked");
	    } else {
	      $('#novice-chk').attr("checked", "checked");
	    }
   }); 
});
//刷新验证码
function coderefresh() {
    var verifyCode = $("#verifyCodeImg");
    var now = new Date();
    verifyCode.attr("src",'I4008lOve893gOfUll983/imageCode.do?pageId=ylbWchatInvest&d=' + now.getTime());
}
//投资检查
function investCheck() {
	var errorTip = $('#errorTip');
    var cash = Number(environment.userCash);
    var investAmountInput = $("#inputAmount");
    var investAmount = investAmountInput.val();
    var maxInvestAmount = Number(product.remain);
    var investableCash = Number(environment.userCash);
    var availableVoucherAmount = Number($("#availableVoucherAmount").html());
    var reg = /^\d+$/;
    if(!reg.test(investAmount)){
    	errorTip.html('请输入50~'+maxInvestAmount+'的整数');
        return false;
    }
    if(isNaN(investAmount*1) || investAmount*1<=0){
    	errorTip.html('请输入正确的金额');
        return false;
    }
    if(investAmount > maxInvestAmount){
    	errorTip.html('投资额不能大于剩余可投额度');
        return false;
    }
    if(investAmount > cash){
    	errorTip.html('您的可用余额不足');
        return false;
    }
    if(investAmount < 50.00){
    	errorTip.html('最小投资金额为'+50.00);
        return false;
    }
    
    if(((maxInvestAmount-investAmount)<50)&&(maxInvestAmount-investAmount)!=0){
        var requiredLeftAmount = Number(maxInvestAmount-50);
        if(requiredLeftAmount > 50){
			errorTip.html('可投金额为'+maxInvestAmount+'或50~'+requiredLeftAmount);
        }else if(requiredLeftAmount <= 50){
        	errorTip.html('可投金额为'+maxInvestAmount);
        }
        return false;
    }

    var verifyCodeInput = $("#authCode");
    var verifyCode = verifyCodeInput.val();
    if(verifyCode == ''){
    	errorTip.html('请输入验证码');
        return false;
    }

    if($('#agreeContract').attr("checked") != "checked"){
    	errorTip.html('请同意共富网投资管理协议');
        return false;
    }
    
    //未实名认证，不能投资
	if($("#realnameFlag").val() == "0"){
		errorTip.html('未实名认证，不能投资');
		$('#realNameBt').show();
		$('#investBt').hide();
        return false;
    }
	
    return true;
}
//投资月息通或新手标
function invest() {
  if(!investCheck()){
    return;
  };
  
  var voucherId = 0;
  if($('#novice-chk').attr("checked") == "checked"){
	voucherId = $("#voucherSelect").val();
  }

  var errorTip = $('#errorTip');
  var investAmount = $("#inputAmount").val();
  var verifyCode = $("#authCode").val();
  
  var param = {};
  param['paramMap.pid'] = product.id;
  param["paramMap.pageId"] = "ylbWchatInvest";
  param["paramMap.code"] = verifyCode;
  param['paramMap.amount'] = investAmount;
  param['paramMap.voucherId'] = voucherId;
  
  $.ajax({
          dataType: 'json',
          url: environment.basePath+"/ylbFinanceInvest.do",
          data: param,
          type: 'POST',
          beforeSend: function() {
              $("#investBt").attr("href","javascript:;").html("正在加入...").addClass("gbtn-disabled");
          },
          success: function(data) {
              if(data.result == 'success'){
            	  alert("恭喜您，投资成功！");
                  window.location.href="/wchatYlbDetail.do?pid="+${productDetailMap.pid};
              }else{
                  if(data.msg == '验证码错误'){
                      coderefresh();
                	  errorTip.html("验证码错误");
                      $("#investBt").attr("href","javascript:invest();").html("我要购买").removeClass("gbtn-disabled");
                  }else{
                	  coderefresh();
                	  errorTip.html(data.msg);
                      $("#investBt").attr("href","javascript:invest();").html("我要购买").removeClass("gbtn-disabled");
                  }
              }
          },
          error: function() {
        	  coderefresh();
        	  errorTip.html("投资失败，请刷新页面或稍后再试");
          }
      });
}

//计算可使用共富券金额
function calAvailableVoucherAmount(){
    var inputAmount = Number($("#inputAmount").val());
    var availableVoucherAmount = $(".availableVoucherAmount");
    for(var i=0,len=availableVoucherAmount.length;i<len;i++){
        var leftAmount = Number($(availableVoucherAmount[i]).attr("leftamount"));
        var voucherType = Number($(availableVoucherAmount[i]).attr("voucherType"));
        var discountRatio = Number($(availableVoucherAmount[i]).attr("discountratio"));
        var discountAmount = Number($(availableVoucherAmount[i]).attr("discountamount"));
        var voucherId = $(availableVoucherAmount[i]).attr("voucherid");
        var typeTitle = $(availableVoucherAmount[i]).attr("typetitle");
        var useVoucher=$('#voucher' + voucherId);
        if(voucherType == 1){
            var availableAmount = inputAmount*discountRatio;
            if(availableAmount > leftAmount){
              availableAmount = leftAmount;
            }
        }
       
        if(isNaN(availableAmount)){
            availableAmount = 0;
        }
        useVoucher.html(typeTitle + "￥" + availableAmount.toFixed(2));
        useVoucher.attr("useVoucherAmount", availableAmount.toFixed(2));
    }
}
</script>
	</body>
</html>